<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 头部提示 -->
      <el-row>
        <el-col>
          <el-alert
            title="注意：只允许设置为第三级分类设置相关参数"
            type="warning"
            show-icon
            :closable="false"
          >
          </el-alert>
        </el-col>
      </el-row>

      <!-- 分类选择 -->
      <el-row class="tyepsele">
        <el-col>
          选择商品分类：<el-cascader
            v-model="selectedKyes"
            expand-trigger="hover"
            :options="Catelist"
            :props="cateprops"
            @change="handlChange"
          >
          </el-cascader>
        </el-col>
      </el-row>

      <!-- 页签 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            @click="addDialogVisable = true"
            :disabled="isBtnDisabled"
            type="primary"
            >添加参数</el-button
          >
          <!-- 动态参数属性 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="deleteParams(index,scope.row)" closable v-for="(item,index) in scope.row.attr_vals" :key="index">
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作" prop="">
              <template slot-scope="scope">
                <el-button
                  @click="showEditDialog(scope.row.attr_id)"
                  type="primary"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  @click="removeParams(scope.row.attr_id)"
                  type="danger"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button
            @click="addDialogVisable = true"
            :disabled="isBtnDisabled"
            type="primary"
            >添加属性</el-button
          >
          <!-- 静态属性 -->
          <el-table :data="onlyTableData" border stripe>
             <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="deleteParams(index,scope.row)" closable v-for="(item,index) in scope.row.attr_vals" :key="index">
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作" prop="">
              <template slot-scope="scope">
                <el-button
                  @click="showEditDialog(scope.row.attr_id)"
                  type="primary"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  @click="removeParams(scope.row.attr_id)"
                  type="danger"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      width="50%"
      :title="titleText"
      :visible.sync="addDialogVisable"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数 -->
    <el-dialog
      width="50%"
      :title="'修改' + titleText"
      :visible.sync="editDialogVisable"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      Catelist: [],
      cateprops: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      selectedKyes: [],
      activeName: 'many',
      //   动态参数数据
      manyTableData: [],
      //   静态属性数据
      onlyTableData: [],
      addDialogVisable: false,
      addForm: {
        attr_name: '',
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      editDialogVisable: false,
      editForm: {},
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      
    }
  },
  created() {
    this.getCatelist()
  },
  methods: {
    //获取商品分类信息
    async getCatelist() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }

      this.Catelist = res.data
    },
    async handlChange() {
      this.getParamsData()
    },
    // 这是tab页签的点击事件
    handleTabClick() {
      this.getParamsData()
    },
    async getParamsData() {
      if (this.selectedKyes.length !== 3) {
        this.selectedKyes = []
        this.manyTableData=[]
        this.onlyTableData=[]
        return
      }
      // 根据所选分类的id，和当前所处的面板，获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败！')
      }
      res.data.forEach((item) => {
        item.attr_vals =item.attr_vals? item.attr_vals.split(' ') : []
        //添加布尔值 控制文本框的显示与隐藏
        item.inputVisible=false
        item.inputValue=''
      })

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )

        if (res.meta.status !== 201) {
          this.$message.error('创建失败！')
        }
        this.$message.success('创建成功')
        this.addDialogVisable = false
        this.getParamsData()
      })
    },
    // 修改参数
    async showEditDialog(rowid) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${rowid}`,
        {
          params: { attr_sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('查询参数失败')
      }
      this.editForm = res.data
      this.editDialogVisable = true
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )

        if (res.meta.status !== 201) {
          this.$message.error('更新失败！')
        }
        this.$message.success('更新成功')
        this.editDialogVisable = false
        this.getParamsData()
      })
    },
    //删除参数
    async removeParams(rowid) {
      const confirmResult = await this.$confirm(
        '此操作将删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${rowid}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      this.getParamsData()
    },
    //文本框失去焦点 或按下enter建 都会触发
   async handleInputConfirm(row){
        if(row.inputValue.trim().length===0){
            row.inputValue=''
            row.inputVisible = false;
            return
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputVisible=false
        row.inputValue=''

        //发起网络请求将新增的值保存到数据库中
       this.savaAttrVales(row)
    },
    showInput(row){
       row.inputVisible=true
    //    让文本框自动获得焦点
    // $nextTick 作用是当页面上的元素被重新渲染后，才会指定回调函数中的代码
       this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
   async savaAttrVales(row){
        //发起网络请求将新增的值保存到数据库中
       const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
             attr_name:row.attr_name,
             attr_sel:row.attr_sel,
             attr_vals:row.attr_vals.join(' ')

       })
        if(res.meta.status!==200){
            return this.$message.error('修改参数项失败')
        }
        this.$message.success('修改参数项成功！')
    },
    deleteParams(i,row){
     row.attr_vals.splice(i,1)
     this.savaAttrVales(row)
    }
  },
  computed: {
    //如果按钮需要被禁用，则返回true 否则返回false
    isBtnDisabled() {
      if (this.selectedKyes.length !== 3) {
        return true
      }
      return false
    },
    //当前选中的三级分类ID
    cateId() {
      if (this.selectedKyes.length == 3) {
        return this.selectedKyes[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>
<style  scoped>
.tyepsele {
  margin: 15px 0;
}
.el-table {
  margin-top: 15px;
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>